"use strict";

const _ = require("lodash");
const moment = require('moment');
const appRoot = require('app-root-path');
const osSystem = require("os");
const HTTPClientService = require("moleculer-http-client");
const fs = require("fs");
const path = require("path");
const mime = require("mime-types");

const { ValidationError,MoleculerError } = require("moleculer").Errors;


/**
 * @typedef {import('moleculer').Context} Context Moleculer's Context
 */

module.exports = {
	name: "http",
	version: 1,
	/**
	 * Mixins
	 */
	mixins: [HTTPClientService],

	/**
	 * Settings
	 */
	settings: {
		messageGatewayUrl:'http://39.100.84.38:8083',
		messageGatewayUser:'ykl',
		messageGatewayPassword:'12345',
		excludeDBService:['list','create','get','update','remove'],//屏蔽所有框架自动生成的接口
		httpClient:{
			/**
			 *  @type {Boolean} Whether to log or not the requests
			 *  框架Bug，默认为 true, 为true 时，启用多实例报错，原因未知
			 */
			logging:false,
		}
	},

	/**
	 * Action Hooks
	 */
	hooks: {
		before: {
			/**
			 * Register a before hook for the `create` action.
			 * It sets a default value for the quantity field.
			 *
			 * @param {Context} ctx
			 */
			create(ctx) {
				ctx.params.quantity = 0;
			}
		}
	},

	/**
	 * Actions
	 */
	actions: {

		/**
		 * 登陆 MessageGatewayApi 获取 token
		 *
		 * @returns 登陆成功，返回 token 登陆失败返回 error
		 */
		loginMessageGateway: {
			rest: {
				method: "GET",
				path: "/message/gateway/login"
			},
			async handler(ctx) {
				try{
					let response = await this.actions.post({
						url:`${this.settings.messageGatewayUrl}/login`,
						opt:{ responseType:"json", json:{ account:`${this.settings.messageGatewayUser}`, password:`${this.settings.messageGatewayPassword}` } }
					});
					let token = response.headers['token'] || response.headers['authorization'] || response.body.token;
					return {code:200,token};
				}catch (e) {
					this.logger.error(e);
					return {code:e.code,statusCode:e.data.statusCode,message:e.data.message};
				}
			}
		},


		/**
		 * 从指定的URL 下载文件
		 *
		 * @returns 登陆成功，返回 token 登陆失败返回 error
		 */
		downLoadFile: {
			rest: {
				method: "GET",
				path: "/download/from/http"
			},
			async handler(ctx) {
				try{
					const filePath = path.join(appRoot + "", "abc.pdf");
					await this.actions.get({
						url:`http://localhost:3000/api/v1/http/download/pdf`,
						opt:{ isStream:true}
					}).then(res =>{
						res.pipe(fs.createWriteStream(filePath,{ encoding: "utf8" }));
						res.on("response", response => {
							if(response.headers && response.headers["content-disposition"]){
								let contentDisposition = response.headers["content-disposition"];
								let fileName = contentDisposition.split(";");
								if(fileName && _.isArray(fileName) && fileName.length > 1 && fileName[1].startsWith("filename=")){
									fileName = fileName[1].split("=")[1];
									let newFilePath = path.join(appRoot+"","new_"+fileName);
									fs.rename(filePath,newFilePath, (err) => {
										if (err){
											throw err;
										}
										console.log('重命名完成');
									});
								}
							}
							this.logger.info(response.headers);
							this.logger.info(response.statusCode);
							this.logger.error(moment().utc().format('YYYY-MM-DD HH:mm:ss.SSS'));
						});
					}).catch(error => {
						this.logger.error(error);
					});
					return {code:200};
				}catch (e) {
					this.logger.error(e);
					return {code:e.code,statusCode:e.data.statusCode,message:e.data.message};
				}
			}
		},


		/**
		 * @summary 保存 终端移动网络发送来的数据消息
		 * @description 保存 终端移动网络发送来的数据消息
		 * @router post /upgrade/file/:id/:upgradeId/:srcAddress
		 * @request body dcs message
		 * @response 200
		 */
		downloadPdf:{
			rest:{
				method:'GET',
				path:'/download/pdf',
			},
			cache:false,
			timeout: 0,
			async handler(ctx) {
				const fileName = "WebGL.pdf";
				const filePath = path.join(appRoot+"", fileName);
				if (!fs.existsSync(filePath))
					throw new MoleculerError("未找到文件");
				const status = fs.statSync(filePath,{bigint:true});
				ctx.meta.$responseType = mime.lookup(filePath);
				ctx.meta.$filename = fileName;
				ctx.meta.$contentLength = status.size;
				return fs.createReadStream(filePath);
			}
		},
	},

	/**
	 * Methods
	 */
	methods: {


	},

	/**
	 * Fired after database connection establishing.
	 */
	async afterConnected() {

	}
};
